#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry
import os
import importlib
import sys
# from jarryLibs.JQt.InitQtModule import *
from JTK.jQt.InitQtModule import *
# from unipath import Path
from JTK.jcore.JFile.JJson import JJson
# import jarryLibs.dict2json as jd2j
# import jarryLibs.RenderQss as rq
import JTK.jQt.RenderQss as rq

# import data.loadMainUI
from .data import __CURRENT_PATH__
from .data.PluginPageWidget import PluginPageWidget
from .data.SceneCheckToolMain import SceneCheckToolMainWindow
from ThreadClass import ThreadClass

try:
    import maya.cmds as cmds
    import JTK.jmaya.core as jmc
    importlib.reload(jmc)
except:
    pass


class PageWidget(PluginPageWidget):
    def __init__(self, parent=None):
        super(PageWidget, self).__init__(parent)
        self.setupUi(self)


class MainUI(SceneCheckToolMainWindow):
    ICONPATH = __CURRENT_PATH__.child('data').child('icons')
    QSSPATH = __CURRENT_PATH__.child('data').child('qss')

    def __init__(self, parent=None):
        super(MainUI, self).__init__(parent)
        self.setupUi(self)
        self.setObjectName('SceneCheckToolMainWindow')
        self.page = {}
        self.thread = {}
        self.setup_ui()
        # self.setStyleSheet(rq.RenderQss(self.QSSPATH.child('main.qss')))
        self.checkInfo_pb.clicked.connect(self.run_check)
        self.checkScript_lw.clicked.connect(self.item_clicked_show)
        self.preset_cb.currentIndexChanged.connect(self.loadConfig)

        self.refsrsh_tb.clicked.connect(self.loadConfig)
        self.removeS_tb.clicked.connect(self.remove_item)

    def setup_ui(self):
        self.refsrsh_tb.setIcon(QIcon(self.ICONPATH.child('refresh.png')))
        self.removeS_tb.setIcon(QIcon(self.ICONPATH.child('remove.png')))
        self.setup_preset_combox()
        self.loadConfig()

    def setup_preset_combox(self):
        config_list = __CURRENT_PATH__.child('data').child('config').listdir('*.json')
        # self.preset_cb=QComboBox()
        self.preset_cb.addItems([c.stem for c in config_list])

        try:
            n = 0
            current_file = mu.sceneName()
            if 'els_' in os.path.basename(current_file):
                if 'ani' in current_file:
                    n = self.get_project_index('ELSAni')
                if 'ani_lay' in current_file or 'lay' in current_file:
                    n = self.get_project_index('ELSLay')
            else:
                import elsLibs.AssetInfoFromFile as elsaif
                # reload(elsaif)
                aif = elsaif.AssetInfoFromFile(current_file)
                self.asset_name = aif.get_name
                self.shortType = aif.get_shortType
                self.step = aif.get_step
                # print self.step
                if self.step == 'mod' or self.step == 'lowmod':
                    # self.preset_cb=QComboBox()
                    n = self.get_project_index('ELSMod')
                elif self.step == 'lookdev' or self.step == 'surface':
                    n = self.get_project_index('ELSLookdev')
                elif self.step == 'rig':
                    n = self.get_project_index('ELSRig')
                elif self.step == 'hair':
                    n = self.get_project_index('ELSHair')
                elif self.step == 'lay':
                    n = self.get_project_index('ELSLay')
                elif self.step == 'ani':
                    n = self.get_project_index('ELSAni')
                else:
                    n = 0
            self.preset_cb.setCurrentIndex(n)
        except:
            cmds.warning('can not check this file!')

    def get_project_index(self, name):
        # 得到对应阶段的插件选项
        count = self.preset_cb.count()
        for n in range(count):
            if self.preset_cb.itemText(n) == name:
                return n
        return 0

    def loadConfig(self):
        self.checkScript_lw.clear()
        for key in self.page:
            self.page[key].hide()
        config_text = self.preset_cb.currentText()
        config_file = __CURRENT_PATH__.child('data').child('config').child('%s.json' % config_text)
        print(config_file)
        config_data = JJson(config_file).read()
        if not config_data:
            cmds.warning('can not loading %s' % config_file)
            return
        for s_data in config_data['checkScript']:
            s_name = s_data['name']
            s_label = s_data['label']
            s_hasFix = eval(s_data['hasFix'])
            item = QListWidgetItem()
            item.setText(s_name)
            item.setToolTip(s_label)
            item.path = s_name
            if 'path' in s_data:
                item.path = s_data['path']

            if s_hasFix:
                item.setIcon(QIcon(self.ICONPATH.child('checkIdleHasFix.png')))
            else:
                item.setIcon(QIcon(self.ICONPATH.child('checkIdle.png')))

            self.checkScript_lw.addItem(item)

            page_widget = PageWidget()
            page_widget.name_le.setText(s_label)
            page_widget.fix_pb.setEnabled(s_hasFix)
            page_widget.selectError_pb.clicked.connect(self.select_error)
            page_widget.check_pb.clicked.connect(self.run_current_check)
            page_widget.fix_pb.clicked.connect(self.fix_current_check)

            self.page[s_name] = page_widget
            self.body_layout.addWidget(self.page[s_name])
            page_widget.hide()
            self.checkScript_lw.setCurrentItem(item)
            self.item_clicked_show()

    def remove_item(self):
        item_row = self.checkScript_lw.currentRow()
        self.checkScript_lw.takeItem(item_row)

    def item_clicked_show(self, *args):
        for p in self.page:
            self.page[p].hide()
        item = self.checkScript_lw.currentItem()
        name = item.text()
        page_widget = self.page[name]
        page_widget.show()
        script_path = item.path
        info_file = __CURRENT_PATH__.child('checkScript')
        for s in script_path.split('.')[:-1]:
            info_file = info_file.child(s)
        info_file = info_file.child('info.html')
        # print info_file
        if info_file.exists():
            d = info_file.read_file(mode='r')

            if '<img src' in d:
                d = d.replace('src="./', 'src="%s/' % info_file.parent)
                # print d
            page_widget.descript_tb.setHtml(d)

    def updata_result_text(self, name, log, status, *args, **kwargs):
        page_widget = self.page[name]
        items = self.checkScript_lw.findItems(name, Qt.MatchContains)
        if log:
            if 'Error:' in log:
                log = "<font color=\"#FF0000\"><b>" + log + "</b></font> "
            elif 'Warning:' in log:
                log = "<font color=\"#ffaa00\"><b>" + log + "</b></font> "
            elif 'Succeed:' in log:
                # log = "<font color=\"#ffaa00\"><b>" + log + "</b></font> "
                log = "<font color=\"#007900\">" + log + "</font> "

            page_widget.checkOutput_tb.append(log)
        if status == 'working' and items:
            item = items[0]
            item.setSelected(True)
            item.setIcon(QIcon(self.ICONPATH.child('checkProcessing.png')))
        elif status == 'checkFailed' and items:
            item = items[0]
            item.setSelected(True)
            item.setIcon(QIcon(self.ICONPATH.child('checkFailed.png')))
        elif status == 'checkSucceeded' and items:
            item = items[0]
            item.setIcon(QIcon(self.ICONPATH.child('checkSucceeded.png')))
        elif status == 'fixFailed' and items:
            item = items[0]
            item.setSelected(True)
            item.setIcon(QIcon(self.ICONPATH.child('fixFailed.png')))
        elif status == 'fixSucceeded' and items:
            item = items[0]
            item.setIcon(QIcon(self.ICONPATH.child('fixSucceeded.png')))
        elif status == 'checkWarning' and items:
            item = items[0]
            item.setIcon(QIcon(self.ICONPATH.child('checkWarning.png')))

    def select_error(self):
        result = self.sender().parent().parent().checkOutput_tb.toPlainText()
        if 'Error:' in result or 'Warning:' in result:
            error_node_str = result.replace('Error:', '').replace('Warning:', '')
            if '[' in error_node_str and ']' in error_node_str:
                st_index = error_node_str.index('[')
                ed_index = error_node_str.index(']')
                error_node_str = error_node_str[st_index:ed_index+1]
            try:
                error_node = eval(error_node_str)
            except:
                error_node_str = error_node_str.strip()
                node_list = error_node_str.split(' ')
                error_node = []
                for node in node_list:
                    # node = node.replace(';','')
                    # print node
                    # print node.split(':[')[-1]
                    try:
                        error_node += eval('[' + node.split(':[')[-1])
                    except:
                        pass

            import maya.cmds as cmds
            cmds.select(cl=1)

            for node in error_node:
                if cmds.objExists(node):
                    cmds.select(error_node, add=1)
            print(cmds.ls(sl=1))

    def run_check(self):
        '''
            批量运行列表中的插件，按检查模式
        '''
        count = self.checkScript_lw.count()
        script_list = []
        for i in range(count):
            item = self.checkScript_lw.item(i)
            name = item.text()
            item.setSelected(True)
            page_widget = self.page[name]
            page_widget.checkOutput_tb.clear()
            script_list.append(item.path)
            item.setIcon(QIcon(self.ICONPATH.child('checkIdle.png')))
            item.setSelected(False)
        self.thread = ThreadClass(script_list, parent=self)
        self.thread.log.connect(self.updata_result_text)
        self.thread.start()

    def run_current_check(self):
        '''
            运行列当前选中的的插件，按检查模式
        '''
        script_list = []
        item = self.checkScript_lw.currentItem()
        name = item.text()
        page_widget = self.page[name]
        page_widget.checkOutput_tb.clear()
        script_list.append(item.path)
        # print script_list
        item.setIcon(QIcon(self.ICONPATH.child('checkIdle.png')))
        self.thread = ThreadClass(script_list, parent=self)
        self.thread.log.connect(self.updata_result_text)
        self.thread.start()

    def fix_current_check(self):
        '''
            运行列表中选中的插件，修复模式
        '''
        script_list = []
        item = self.checkScript_lw.currentItem()
        name = item.text()
        page_widget = self.page[name]
        page_widget.checkOutput_tb.clear()
        script_list.append(item.path)
        item.setIcon(QIcon(self.ICONPATH.child('checkIdle.png')))
        self.thread = ThreadClass(script_list, fix=True, parent=self)
        self.thread.log.connect(self.updata_result_text)
        self.thread.start()


def run():
    # import pymel.core as pm
    # import jarryLibs.mayakit.getMayaWindow as gmw
    from JTK.jmaya.core.get_main_window import get_main_window
    name = 'SceneCheckToolMainWindow'
    if cmds.window(name, q=1, ex=1):
        cmds.deleteUI(name)
    ui = MainUI(parent=get_main_window())
    ui.show()


if __name__ == "__main__":
    app = QApplication([])
    my_ui = MainUI()
    my_ui.show()
    app.exec_()
